<template>
  <!-- 渠道页面 -->
  <div class="channel-status">
    <div class="contents">
      <!-- 顶部文本 -->
      <div class="describe">
        <div class="text">
          <p>
            1、格子上的数字代表在渠道售卖的房间数量，最多不会超过房型的剩余房量。
          </p>
          <p>
            2、单击格子可以快速打开、关闭房态，或修改售卖房量。
          </p>
          <p>
            3、点击“批量修改”可批量管理渠道房态；若想同时修改多个渠道的房态，请点击“多渠道修改”。
          </p>
          <p>
            4、携程直连下无法管理合同保留房的房态，请谨慎直连。
          </p>
        </div>
      </div>
      <!--END 顶部文本 -->

      <!-- 选择渠道 -->
      <el-radio-group v-model="select_channel_id" size="small" @change="Change_select_channel" style="margin-top: 20px;">
        <el-radio-button :label="item.channel_id" v-for="item in channel_Button_List" :key="item.channel_id">
          {{ item.name }}
        </el-radio-button>
        <!-- <el-radio-button label="1" class="localButton">本地</el-radio-button> -->
        <!-- <el-radio-button label="1" class="localButton">小程序</el-radio-button> -->

      </el-radio-group>


      <div class="filter">
        <div class="left">
          <!-- 选择日期 -->
          <div class="select_date">
            <div class="el-icon-arrow-left change_Date_Icon" @click="change_Date(0)"></div>
            <div class="row_input_date_picke">
              <el-date-picker v-model="date" size="small" style="width:125px;" :clearable='false' :default-value="date"
                value-format="yyyy-MM-dd" format="MM-dd" type="date">
              </el-date-picker>
              <div class="row_input_date_picke_text">
                入住
                <i class='el-icon-date'></i>
              </div>
            </div>
            <div class="el-icon-arrow-right change_Date_Icon" @click="change_Date(1)"></div>
          </div>
          <!-- 选择房型 -->
          <el-select v-model="roomValue" @change="Change_select_room" class="select_room" style="margin-left:20px"
            placeholder="全部房型">
            <el-option v-for="item in roomOptions" :key="item.id" :label="item.pms_title" :value="item.id">
            </el-option>
          </el-select>
          <!-- 房间状态 -->
          <div class="roomStatus">
            <div class="roomStatus_item">
              <div class="roomStatus_sale"></div> 可售
            </div>
            <div class="roomStatus_item">
              <div class="roomStatus_stop_sale roomStatus_sale"></div> 停售
            </div>
            <div class="roomStatus_item">
              <div class="roomStatus_not_sale roomStatus_sale"></div> 售罄
            </div>
          </div>
        </div>

        <div class="right">
          <el-button @click="openEdit" size="small">批量修改</el-button>
          <el-button size="small" :disabled="true">修改记录</el-button>
        </div>
      </div>


      <!-- 房态表格 -->
      <el-table :data="tableData" :style="{ 'width': '100%', 'margin-top': '15px', 'height': maxHeight, }" border
        class="table" :header-cell-style="{ background: '#FAFAFA' }" :key="tablekey" :max-height="maxHeight">
        <el-table-column prop="title" width="200" align="center">
          <template slot="header">
            <div class="table_header_date">{{ select_channel ? select_channel.name : '' }}房型</div>
          </template>
        </el-table-column>
        <el-table-column width="120" v-for="( item, index ) in  dateArr " :key="index" align="center">
          <!-- 日期-->
          <template slot="header">
            <div class="table_header_date">
              <div :style="{ 'color': formatDate(new Date()) == item ? '#F56C6C' : '' }">
                <span>{{ formatDate(new Date()) == item ? '今天' : item.substring(5) }}</span>
                <p>周{{ handlweek(item) }}</p>
              </div>
            </div>
          </template>

          <el-table-column width="95" align="center">
            <template slot="header">
              <div class="table_header_date"> 剩 {{ tableDataStock ? tableDataStock[item] : '--' }} 间</div>
            </template>
            <template slot-scope="{row}">
              <div class="table_sale_cell">
                <div
                  v-if="row.stock_info[item] && row.stock_info[item].status == 1 || row.stock_info[item] && row.stock_info[item].status == 0">
                  <el-popover width="200" trigger="click" :visible-arrow="false">
                    <div class="setStock_popover">
                      <div>房型 : <span>{{ row.title }}</span></div>
                      <div>时间 : <span>{{ item }} 周{{ handlweek(item) }}</span></div>
                      <div class="">
                        售卖数量 :
                        <span> <el-input v-model="popover_data.saleNumber" size="mini"
                            style="width: 100px;"></el-input></span>
                      </div>
                      <div class="">房态 :
                        <span style="">
                          <el-radio v-model="popover_data.status" :label="0">关闭</el-radio>
                          <el-radio v-model="popover_data.status" :label="1">打开</el-radio>
                        </span>
                      </div>
                      <div class="room-state">
                        <div class="">
                          <el-button size="mini" @click="cancell">取消</el-button>
                          <el-button type="primary" size="mini" @click="submit_day">确定</el-button>
                        </div>
                      </div>
                    </div>

                    <div class="roomNum" slot="reference">
                      <div @click="click_sale_room(row, item)">
                        <!-- 可售 -->
                        <div v-if="row.stock_info[item] && row.stock_info[item].status == 1"
                          class="table_has_sale table_sale">
                          {{ row.stock_info ? row.stock_info[item].stock_num : '--' }}
                        </div>
                        <!-- 停售 -->
                        <div v-if="row.stock_info[item] && row.stock_info[item].status == 0"
                          class="table_stop_sale table_sale">
                          <i class="iconfont icon-solid-home"></i>
                          <p>停售</p>
                        </div>
                      </div>
                    </div>
                  </el-popover>
                </div>
                <!-- 售罄 -->
                <div v-else-if="row.stock_info[item] && row.stock_info[item].status == 2"
                  class="table_not_sale table_sale">
                  <i class="iconfont icon-solid-home"></i>
                  <p>售罄</p>
                </div>
                <div v-else>--</div>
              </div>
            </template>
          </el-table-column>

        </el-table-column>
      </el-table>
    </div>
    <!-- 批量修改对话框 -->
    <el-dialog class="edit" title="批量修改" :visible.sync="edit" width="500px">
      <div class="edit_dialog">
        <!-- 日期 -->
        <div class="time">
          <span>日期：</span>
          <el-date-picker value-format="yyyy-MM-dd" size="small" v-model="batchEditTime" type="daterange"
            range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
          </el-date-picker>
        </div>
        <!-- 渠道 -->
        <div class="channel edit_dialog_item">
          <span>渠道：</span>
          <el-select v-model="channelValue_dialog" placeholder="请选择" size="small">
            <el-option v-for="item in channel_dialog" :key="item.channel_id" :label="item.name" :value="item.channel_id">
            </el-option>
          </el-select>
        </div>
        <!-- 房型 -->
        <div class="edit_dialog_item">
          <span>房型：</span>
          <el-checkbox v-model="checkAll" @change="handleCheckAllChange">
            全选
          </el-checkbox>
          <div style="margin-top: 15px ;"></div>
          <el-checkbox-group v-model="checkedRoom" style="display:flex;flex-direction:column;margin-left: 60px;"
            @change="handleCheckedCitiesChange">
            <el-checkbox v-for="(item, index) in roomApartments_dialog" :label="item.id" :key="index">
              {{ item.pms_title }}
              <el-input v-model="item.stock" size="mini" style="width: 100px;margin-left: 10px;"></el-input>
            </el-checkbox>
          </el-checkbox-group>

        </div>
        <!-- 批量修改 -->
        <div class="edit_dialog_item">
          <span>批量修改：</span>
          <el-input size="mini" v-model="batchStock" type="text" style="width:120px;margin-top:10px"
            @blur="change_dialog_stock"></el-input>
          <span style="margin-left:10px;color: #a3a1a1;">所有房型，每一天的售卖数量</span>
        </div>
        <!-- 房态 -->
        <div class="edit_dialog_item">
          <span>房态：</span>
          <el-radio v-model="batchEditStatus" :label="0">关闭</el-radio>
          <el-radio v-model="batchEditStatus" :label="1">打开</el-radio>
        </div>
        <div class="edit_dialog_item" style="display:flex;justify-content:flex-end;">
          <el-button size="mini">取消</el-button>
          <el-button type="primary" size="mini" @click="submit_days">确定</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getdaysAgo, getDateArr, handleDate } from "../../../../api/countDay"//关于日期的方法
import { cloneDeep } from 'lodash'

export default {
  data() {
    return {
      maxHeight: window.innerHeight - 435,
      hotel_id: sessionStorage.getItem('hotel_id'),
      select_channel_id: 2,//当前选中渠道
      select_channel: null,
      channel_Button_List: [],//渠道按钮组列表
      date: new Date(),//选择日期
      dateArr: getDateArr(getdaysAgo(new Date(), 2, true), getdaysAgo(new Date(), 27)),//获取日期数组。
      tableData: [],//表格数据
      tableDataStock: null,//表格库存数据
      tablekey: true,//表格key值
      roomOptions: [],//房型选择器
      roomValue: null,
      // 气泡框数据
      popover_data: {
        saleNumber: null,//气泡框售卖数量
        status: null,//气泡框售卖数量
        date: null,
        room_id: null,
      },

      // 批量修改对话框
      edit: false,//对话框
      roomApartments_dialog: [],//批量修改房型
      channel_dialog: [],//渠道选择器
      batchStock: null,//批量修改库存
      channelValue_dialog: null,//批量修改选择渠道
      batchEditTime: null,//批量修改日期
      batchEditStatus: 1,//批量修改状态
      checkedRoom: [],//批量修改选中的房间
      checkAll: false,


      radio: '',
      value1: '',
      value: '',

      options: [{
        value: '选项1',
        label: '黄金糕'
      }, {
        value: '选项2',
        label: '双皮奶'
      }, {
        value: '选项3',
        label: '蚵仔煎'
      }, {
        value: '选项4',
        label: '龙须面'
      }, {
        value: '选项5',
        label: '北京烤鸭'
      }],

    };
  },
  watch: {
    date(n) {
      // console.log(n, 'date')
      this.dateArr = getDateArr(getdaysAgo(n, 2, true), getdaysAgo(n, 27))//重新获取日期数组
      this.getRoomStock()//重新获取库存
      this.getChannelRoom()//重新获取房间信息
      this.tablekey = !this.tablekey//刷新table数据
    },
  },
  created() {
    this.getChannel()
  },
  mounted() {
    // 监听窗口大小变化
    window.addEventListener('resize', this.handleResize);
  },
  beforeDestroy() {
    // 移除窗口大小变化的监听
    window.removeEventListener('resize', this.handleResize);
  },
  methods: {
    // 监听表格高度
    handleResize() {
      // 在这里处理窗口大小变化的逻辑
      let screenWidth = window.innerWidth;
      let screenHeight = window.innerHeight;
      // console.log(screenWidth, '宽');
      // console.log(screenHeight, '高');
      // 425 除了表格其它元素的高度
      this.maxHeight = screenHeight - 425
      // 更新相关数据或执行其他操作
    },
    // 批量修改售卖数量====改变房型值
    change_dialog_stock() {
      this.roomApartments_dialog.forEach(item => {
        item.stock = this.batchStock
      })
    },
    // 点击在售房间
    click_sale_room(row, item) {
      // console.log(item,'item');
      console.log(row, 'row');
      this.popover_data.saleNumber = null
      this.popover_data.status = row.stock_info[item].status
      this.popover_data.date = item
      this.popover_data.room_id = row.room_id
    },
    /**
     * 改变日期
     * @param {*} operate 0往前，1往后
     * 
     */
    change_Date(operate) {
      if (operate == 1) {
        this.date = getdaysAgo(this.date, 28)
      } else if (operate == 0) {
        this.date = getdaysAgo(this.date, 28, true)
      }
    },

    // 气泡框单日确认
    submit_day() {
      if (this.popover_data.saleNumber == null) {
        this.$message.error('请填写售卖数量')
        return
      }
      let data = {
        hotel_id: parseInt(this.hotel_id),
        room_id: this.popover_data.room_id,
        date: this.popover_data.date,
        stock_num: parseInt(this.popover_data.saleNumber),
        channel_id: this.select_channel_id,
        status: this.popover_data.status
      }
      console.log(data, '气泡框单日确认');
      this.my_request('supplier/hotel-pms-channel-stock', data, 'PUT').then(res => {
        console.log(res, 'res');
        let { code, message } = res.data
        if (200 == code) {
          document.body.click()
          this.getRoomStock()//重新获取库存
          this.$message.success(message)
        } else {
          this.$message.error(message)
        }
      })
    },
    // 取消
    cancell() {
      document.body.click()
    },
    submit_days() {
      let roomsList = []
      // console.log(this.roomApartments_dialog, 'roomApartments_dialog');
      // console.log(this.batchEditTime, 'time');
      // console.log(this.checkedRoom, 'checkedRoom');

      // 处理rooms 数据
      this.roomApartments_dialog.forEach(item => {
        roomsList.push({
          room_id: item.id,
          stock_num: item.stock
        })
      })

      let data = {
        hotel_id: this.hotel_id,
        rooms: roomsList,
        channel_id: this.channelValue_dialog,
        start_date: this.batchEditTime[0],
        end_date: this.batchEditTime[1],
        batchEditStatus: this.batchEditStatus
      }
      // console.log(data, 'data');
      this.my_request('supplier/hotel-pms-channel-stock/rooms', data, 'PUT').then(res => {
        // console.log(res);
        let { code, message } = res.data
        if (200 == code) {
          this.edit = false
          this.getRoomStock()
          this.$message.success(message)

        } else {
          // this.$message.error('设置失败')
          this.$message.error(message)
        }
      })
    },
    // 打开批量修改对话框的操作
    openEdit() {
      this.roomApartments_dialog.forEach(item => {
        item.stock = null
      })
      this.batchStock = null
      this.checkedRoom = []
      this.checkAll = false
      this.batchEditStatus = 1
      this.batchEditTime = []
      this.edit = true
    },


    // 获取渠道
    getChannel() {
      let data = {
        hotel_id: this.hotel_id,
      }
      let local = {
        channel_id: 1,
        name: '本地'
      }
      this.my_request('supplier/hotel-pms/price/channel', data, 'GET').then(res => {
        let { code, data } = res.data
        if (200 == code) {
          console.log(data, '获取渠道');
          this.channel_Button_List = data.filter(item => item.channel_id != 1)
          if (this.channel_Button_List && this.channel_Button_List.length > 0) {
            this.select_channel_id = this.channel_Button_List[0].channel_id
            this.select_channel = this.channel_Button_List[0]
          } else {
            this.select_channel_id = local.channel_id
            this.select_channel = local
          }
        
          // 对话框渠道
          this.channel_dialog = cloneDeep(data.filter(item => item.channel_id != 1))
          this.channelValue_dialog = this.channel_dialog[0] ? this.channel_dialog[0].channel_id : 1
          this.channel_dialog.push(local)

          this.getChannelRoom()
          this.getRoomStock()
        }
      })
    },
    // 获取库存
    getRoomStock(roomID) {
      let channelData = {
        hotel_id: this.hotel_id,
        channel_id: this.select_channel_id,
        start_date: this.dateArr[0],
        end_date: this.dateArr[this.dateArr.length - 1],
        room_id: roomID ? roomID : 0
      }
      console.log(channelData, 'channelData');
      this.my_request('supplier/hotel-pms/channel', channelData, 'GET').then(res => {
        console.log(res, '获取库存');
        let { code, data } = res.data
        if (200 == code) {
          this.tableData = data.pms
          this.tableDataStock = data.total
        }
      })
    },
    // 获取房型
    getChannelRoom() {
      let getChannelRoomData = {
        hotel_id: this.hotel_id,
        channel_id: this.select_channel_id
      }
      this.my_request('supplier/hotel-pms/price/channel-room', getChannelRoomData, 'GET').then(res => {
        console.log(res, '获取房型');
        let { code, data } = res.data
        if (200 == code) {

          // 对话框房型
          let list = []
          list = cloneDeep(data)
          list.forEach(item => {
            item.stock = null
          })
          this.roomApartments_dialog = list

          // console.log(this.roomApartments_dialog, ' this.roomApartments_dialog');
          this.roomOptions = cloneDeep(data)
          this.roomOptions.unshift({
            id: 0,
            pms_title: '全部房型'
          })
          this.roomValue = 0
          this.tablekey = !this.tablekey
        }
      })
    },

    // 改变选中的渠道
    Change_select_channel() {
      console.log('Change_select_channel');
      if (this.select_channel_id == 1) {
        this.select_channel = {
          channel_id: 1,
          name: '本地'
        }
      } else {
        this.channel_Button_List.forEach(item => {
          if (item.channel_id == this.select_channel_id) {
            this.select_channel = item
          }
        })
      }
      this.getChannelRoom()
      this.getRoomStock()
      // if (this.select_channel_id==1) {
      //   this.tableData[0].title = '测试'
      // }
      this.tablekey = !this.tablekey
    },
    // 改变选中的房型
    Change_select_room() {
      // this.select_room
      console.log(this.roomValue, 'this.roomValue');
      this.getRoomStock(this.roomValue)
    },

    // 批量修改对话框
    // 全选
    handleCheckAllChange(val) {
      let valueList = []
      this.roomApartments_dialog.forEach(item => {
        valueList.push(item.id)
      })
      this.checkedRoom = val ? valueList : [];


    },
    // 子选择改变
    handleCheckedCitiesChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.roomApartments_dialog.length;

    },



    /**
     * 转换周*
     * @param {*} val 
     */
    handlweek(val) {
      let week = ''
      val = new Date(val).getDay()
      switch (val) {
        case 0:
          week = "日"
          break;
        case 1:
          week = "一"
          break;
        case 2:
          week = "二"
          break;
        case 3:
          week = "三"
          break;
        case 4:
          week = "四"
          break;
        case 5:
          week = "五"
          break;
        case 6:
          week = "六"
          break;
      }
      return week
    },

    /**
    * 转换成字符串格式
    * @param {*} date 
    * @param {*} key true返回MM-dd
    */
    formatDate(date, key) {
      let year = date.getFullYear();
      let month = String(date.getMonth() + 1).padStart(2, '0');
      let day = String(date.getDate()).padStart(2, '0');
      let hours = String(date.getHours()).padStart(2, '0');
      let minutes = String(date.getMinutes()).padStart(2, '0');
      let seconds = String(date.getSeconds()).padStart(2, '0');

      if (key == 1) {
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      } else if (key == 2) {
        return `${month}-${day} ${hours}:${minutes}`;
      } else {
        return `${year}-${month}-${day}`;
      }
    },
  }
}
</script>

<style lang="scss" scoped>
.channel-status {
  width: calc(100% - 30px);
  height: calc(100vh - 155px);
  padding: 15px;
  background-color: white;


  .left {
    display: flex;
    // background-color: #409EFF;

    .roomStatus {
      font-size: 15px;
      display: flex;
      margin-left: 30px;
      align-items: center;
      height: 35px;

      .roomStatus_item {
        display: flex;
        width: 80px;
      }

      .roomStatus_sale {
        width: 18px;
        height: 18px;
        border: #DCDFE6 1px solid;
        border-radius: 4px;
        margin-right: 8px;
      }

      .roomStatus_not_sale {
        background-color: #FFEAEA;
        border-color: #F56C6C;
      }

      .roomStatus_stop_sale {
        background-color: #f2f2f2;

      }
    }
  }

  .contents {
    width: 100%;
    height: 100%;
    background: white;

    .describe {
      height: 120px;
      background: #ecf2ff;
      width: calc(100% - 30px);
      font-size: 15px;
      line-height: 22px;
      display: flex;
      align-items: center;

      .text {
        margin-left: 20px;
      }
    }

    .filter {
      margin-top: 20px;
      display: flex;
      justify-content: space-between;
      height: 38px;

      .right {
        .el-button {
          background-color: #0486fe;
          color: white;
        }
      }
    }

    .table_header_date {
      font-weight: 500;
      color: black;
      font-size: 12px;
      line-height: 15px;
    }

  }

  .table {
    width: 100%;
    // height: 500px;
    // background-color: #aac6e2;
  }

  .table_sale_cell {
    .table_sale {
      padding: 10px 0;

      .icon-solid-home {
        font-size: 25px;
      }
    }

    .table_has_sale {
      height: 72px;
      line-height: 52px;
    }

    .table_has_sale:hover,
    .table_stop_sale:hover {
      cursor: pointer;
    }

    .table_not_sale {
      background-color: #FFEAEA;
      border: #F56C6C 1px solid;

    }

    .table_stop_sale {
      background-color: #f2f2f2;
      border: #f2f2f2 1px solid;
    }

  }

}

// popover气泡框
.setStock_popover {
  div {
    padding-bottom: 5px;
  }

  span {
    margin-left: 5px;

    .el-radio {
      margin-right: 5px;
    }
  }

  .room-state {
    margin-top: 15px;
    padding-bottom: 0px;
    display: flex;
    justify-content: center;
  }
}

// 批量修改对话框
.edit_dialog {

  .edit_dialog_item {
    margin-top: 20px;
  }
}



::v-deep .channel {
  .el-input.el-input--suffix>.el-input__inner {
    height: 32px;
    line-height: 32px;
  }

}

// 按钮组
::v-deep .el-radio-button.localButton {
  margin-left: 25px;

  .el-radio-button__inner {
    border: 1px solid #DCDFE6;
    border-radius: 0px;
    width: 100%;
    box-shadow: 0px 0 0 0 #409EFF;
  }
}

// 房型选择器
::v-deep .select_room.el-select {
  .el-input.el-input--suffix>.el-input__inner {
    height: 35px;

    .el-input__icon {
      line-height: 35px;
    }
  }


  .el-input__inner {
    height: 27px;
    line-height: 28px;
  }

  .el-input__icon {
    line-height: 35px;
  }

  .el-input.el-input--suffix {
    line-height: 28px;
  }
}

// 日期选择器
::v-deep .select_date {
  display: flex;
  border: #DCDFE6 1px solid;
  border-radius: 4px;
  height: 34px;

  .change_Date_Icon {
    width: 25px;
    text-align: center;
    line-height: 34px;
    height: 34px;
  }

  .change_Date_Icon:hover {
    cursor: pointer;
  }

  .el-icon-arrow-left {
    border-right: 1px solid #DCDFE6;
  }

  .el-icon-arrow-right {
    border-left: 1px solid #DCDFE6;
  }

  .row_input_date_picke {
    position: relative;
    width: 100px;
    display: flex;
    // border: 1px solid #DCDFE6;
    // border-radius: 4px;
    border: none;
    font-size: 13px;
    line-height: 32px;
    height: 33px;

    .row_input_date_picke_text {
      height: 30px;

      background-color: white;
      /* 让上层元素不响应鼠标事件 */
      pointer-events: none;
      position: absolute;
      left: 47px;
      display: flex;

      i {
        line-height: 34px;
        margin-left: 4px;
      }
    }
  }

  .el-date-editor.el-input.el-input--small.el-input--prefix.el-input--suffix.el-date-editor--date {
    .el-input__inner {
      padding: 0 10px;
      width: 100px;
      height: 32px;
      line-height: 35px;
      font-size: 13px;
      color: black;
      border: none;
    }

    .el-input__prefix {
      display: none;
    }

  }
}

::v-deep .el-table {
  th.el-table__cell {
    padding: 12px;
    height: 0px;
  }

  .el-table__cell {
    padding: 0px 0;
    height: 72px;
  }

  .cell {
    padding: 0px;
  }
}
</style>